<template>
  <view class="container">
    <!-- 状态筛选 -->
    <view class="status-filter">
      <button 
        v-for="(status, index) in statusFilters" 
        :key="index" 
        :class="{'active': currentStatus === status.value}"
        @click="filterByStatus(status.value)"
      >
        {{status.label}}
      </button>
    </view>
    
    <!-- 列表区域 -->
    <view class="list-container">
      <!-- 列表项 -->
      <view 
        v-for="item in filteredList" 
        :key="item.id" 
        class="rescue-item"
      >
        <!-- 左侧信息 -->
        <view class="item-left">
          <view class="info-header">
            <text class="car-number">车牌:{{item.carNum}}</text>
            <view class="status-tag" :class="getStatusClass(item.status)">{{getStatusText(item.status)}}</view>
          </view>
          
          <view class="info-grid">
            <view class="info-item">
              <text class="label">求助人</text>
              <text class="value">{{item.name}}</text>
            </view>
            <view class="info-item">
              <text class="label">电话</text>
              <text class="value phone" @click.stop="callPhone(item.phone)">{{item.phone}}</text>
            </view>
            <view class="info-item full-width">
              <text class="label">位置</text>
              <text class="value location">{{item.position}}</text>
            </view>
            <view class="info-item">
              <text class="label">类型</text>
              <text class="value">{{getTypeName(item.typeId)}}</text>
            </view>
            <view class="info-item">
              <text class="label">时间</text>
              <text class="value time">{{formatTime(item.time)}}</text>
            </view>
          </view>
        </view>
        <!-- 根据状态显示不同样式和文本的按钮 -->
        <view>
          <button 
            :style="{ backgroundColor: getButtonColor(item.status), color: '#fff' }" 
            @click.stop="handleStatus(item)"
          >
            {{ getButtonText(item.status) }}
          </button>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredList.length === 0">
        <image src="@/static/kong.png" mode="aspectFit"></image>
        <text>暂无救援信息</text>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="isLoading">
        <text>加载中...</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import request from '@/pages/util/request.js';
import baseUrl from '@/pages/util/urlConfig.js';

const rescueList = ref([]);
const filteredList = computed(() => {
  if (!searchKeyword.value) {
    return currentStatus.value ? 
      rescueList.value.filter(item => String(item.status) === currentStatus.value) : 
      rescueList.value;
  } else {
    const keyword = searchKeyword.value.toLowerCase();
    return rescueList.value.filter(item => 
      item.carNum.toLowerCase().includes(keyword) || 
      item.name.toLowerCase().includes(keyword) ||
      item.phone.includes(keyword)
    );
  }
});

const currentStatus = ref('');
const searchKeyword = ref('');
const isLoading = ref(false);
const pageNum = ref(1);
const hasMore = ref(true);

// 状态文本映射
const statusMap = {
  '0': '求助中',
  '1': '已接单',
  '2': '超时',
  '3': '已完成'
};

// 状态样式映射
const statusClassMap = {
  '0': 'status-pending',
  '1': 'status-accepted',
  '2': 'status-overtime',
  '3': 'status-completed'
};

// 救援类型映射
const typeMap = {
  '0': '搭电',
  '1': '轮毂',
  '2': '轮胎',
  '3': '电池',
  '4': '大窗',
  '5': '雨刷器',
  '6': '座椅'
};

// 状态筛选选项
const statusFilters = [
  { value: '', label: '全部' },
  { value: '0', label: '求助中' },
  { value: '1', label: '已接单' },
  { value: '2', label: '超时' },
  { value: '3', label: '已完成' }
];

// 页面加载时调用接口
onMounted(() => {
  getRescueList();
});

// 获取救援列表
const getRescueList = () => {
  if (!hasMore.value || isLoading.value) return;
  
  isLoading.value = true;
  const requestData = {
    pageNum: pageNum.value,
    pageSize: 10,
    status: currentStatus.value
  };
  console.log('请求参数:', requestData); // 添加日志打印请求参数
  request({
    url: baseUrl + '/qxk/rescue/list',
    method: 'GET',
    data: requestData,
    success: (res) => {
      console.log('接口响应数据:', res); // 添加日志打印响应数据
      if (res.data && res.data.code === 200) {
        const newData = res.data.rows || [];
        // 打印获取到的数据，检查 status 字段
        console.log('获取到的新数据:', newData.map(item => ({ id: item.id, status: item.status }))); 
        if (pageNum.value === 1) {
          rescueList.value = newData;
        } else {
          rescueList.value = [...rescueList.value, ...newData];
        }
        
        hasMore.value = newData.length >= 10;
        if (hasMore.value) {
          pageNum.value++;
        }
      } else {
        uni.showToast({
          title: '获取救援列表失败',
          icon: 'none'
        });
        console.error('获取救援列表失败:', res);
      }
      isLoading.value = false;
    },
    fail: (err) => {
      uni.showToast({
        title: '网络请求失败',
        icon: 'none'
      });
      console.error('请求失败:', err);
      isLoading.value = false;
    }
  });
};

// 根据状态筛选
const filterByStatus = (status) => {
  if (currentStatus.value === status) return;
  
  currentStatus.value = status;
  pageNum.value = 1;
  hasMore.value = true;
  getRescueList();
};

// 搜索
const searchRescue = () => {
  pageNum.value = 1;
  hasMore.value = true;
  getRescueList();
};

// 处理状态按钮点击事件
const handleStatus = (item) => {
  uni.showModal({
    title: '确认接单',
    content: `是否确认接取 ${item.carNum} 的救援单？`,
    success: (res) => {
      if (res.confirm) {
        // 正确拼接路径参数（直接传递值，无需键名）
        const apiUrl = `${baseUrl}/qxk/rescue/st/${item.id}/1/${item.phone}`;
        console.log('即将调用的接口 URL:', apiUrl);
        
        request({
          url: apiUrl,
          method: 'PUT',
          // 注意：后端已通过路径获取参数，此处无需重复传递data
          success: (res) => {
            console.log('接口响应数据:', res);
            if (res.data && res.data.code === 200) {
              uni.showToast({
                title: '接单成功',
                icon: 'success'
              });
              // 更新本地数据
              const index = rescueList.value.findIndex(i => i.id === item.id);
              if (index !== -1) {
                rescueList.value[index].status = '1'; // 确保状态为字符串类型
              }
            } else {
              uni.showToast({
                title: res.data.message || '接单失败',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            console.error('请求失败:', err);
            uni.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            });
          }
        });
      }
    }
  });
};

// 获取状态文本
const getStatusText = (status) => {
  return statusMap[status] || '未知状态';
};

// 获取状态样式
const getStatusClass = (status) => {
  return `status-tag ${statusClassMap[status] || ''}`;
};

// 获取救援类型名称
const getTypeName = (typeId) => {
  return typeMap[typeId] || `类型${typeId}`;
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return '';
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
};

// 监听搜索输入
const onSearchInput = (e) => {
  searchKeyword.value = e.detail.value;
};

// 拨打电话
const callPhone = (phone) => {
  uni.makePhoneCall({
    phoneNumber: phone
  });
};


// 页面滚动到底部加载更多
const onReachBottom = () => {
  getRescueList();
};

// 根据状态获取按钮颜色
const getButtonColor = (status) => {
  switch (status) {
    case '0':
      return '#1677ff'; // 求助中，蓝色
    case '1':
      return '#cccccc'; // 已接单，灰色
    case '2':
      return '#ff4d4f'; // 超时，红色
    case '3':
      return '#000000'; // 已完成，黑色
    default:
      return '#1677ff';
  }
};

// 根据状态获取按钮文本
const getButtonText = (status) => {
  switch (status) {
    case '0':
      return '接单'; // 求助中
    case '1':
      return '已接单'; // 已接单
    case '2':
      return '超时'; // 超时
    case '3':
      return '已完成'; // 已完成
    default:
      return '接单';
  }
};
</script>

<style lang="scss">
@function px2rpx($px) {
  @return $px * 2rpx;
}

.container {
  padding: px2rpx(20);
  background-color: #f7f8fa;
  min-height: 100vh;
}

// 搜索栏
.search-bar {
  display: flex;
  margin-bottom: 22rpx;
  
  .search-input {
    flex: 1;
    height: 150rpx;
	width: 200rpx;
    background-color: #fff;
    border-radius: px2rpx(36);
    display: flex;
    align-items: center;
    padding: 0 px2rpx(24);
    box-shadow: 0 px2rpx(2) px2rpx(8) rgba(0, 0, 0, 0.05);
    
    .search-icon {
      color: #999;
      margin-right: px2rpx(12);
      font-size: px2rpx(30);
    }
    
    input {
      flex: 1;
      font-size: px2rpx(28);
      color: #333;
    }
    
    .placeholder {
      color: #999;
    }
  }
  
  .search-btn {
    width: px2rpx(140);
    height: px2rpx(72);
    line-height: px2rpx(72);
    text-align: center;
    background-color: #1677ff;
    color: #fff;
    border-radius: px2rpx(36);
    margin-left: px2rpx(20);
    font-size: px2rpx(28);
    
    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
  }
}

// 状态筛选
.status-filter {
  display: flex;
  margin: bottom 20rpx;
  
  button {
    padding:5rpx;
    margin: 8rpx;
    border-radius: 20rpx;
    font-size: 40rpx;
    background-color: #fff;
    color: #666;
    border: none;
    
    &.active {
      background-color: #1677ff;
      color: #fff;
    }
    
    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
  }
}

// 列表容器
.list-container {
  .rescue-item {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    overflow: hidden;
    
    &:active {
      transform: translateY(px2rpx(2));
    }
    
    .item-left {
      padding: 24rpx;
      flex: 1;
    }
    
    .item-right {
      display: flex;
      align-items: center;
      padding-right: 24rpx;
    }
  }
  
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: px2rpx(20);
    
    .car-number {
      font-size: px2rpx(32);
      font-weight: bold;
      color: #333;
    }
    
    .status-tag {
      padding: px2rpx(6) px2rpx(16);
      border-radius: px2rpx(18);
      font-size: px2rpx(24);
      font-weight: 500;
    }
    
    .status-pending {
      background-color: #FFEBEB;
      color: #FF4D4F;
    }
    
    .status-accepted {
      background-color: #E6F7FF;
      color: #1890FF;
    }
    
    .status-overtime {
      background-color: #FFF7E6;
      color: #FA8C16;
    }
    
    .status-completed {
      background-color: #F6FFED;
      color: #52C41A;
    }
  }
  
  .info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16rpx;
    
    .info-item {
      .label {
        font-size: 24rpx;
        color: #666;
        display: block;
        margin-bottom: 4rpx;
      }
      
      .value {
        font-size: 28rpx;
        color: #6b6d62;
        word-break: break-all;
        
        &.phone {
          color: #1677ff;
          text-decoration: underline;
        }
        
        &.location {
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        
        &.time {
          color: #999;
          font-size: 24rpx;
        }
      }
      
      &.full-width {
        grid-column: 1 / -1;
      }
    }
  }
  
  .action-btn {
    background-color: #1677ff;
    color: #fff;
    border-radius: 32rpx;
    padding:32rpx;
	width: 400rpx;
    font-size: 28rpx;
    
    &:active {
      opacity: 0.8;
      transform: scale(0.98);
    }
  }
  
  .empty-state {
    padding: px2rpx(80) 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    image {
      width: px2rpx(200);
      height: px2rpx(200);
      margin-bottom: px2rpx(30);
      opacity: 0.5;
    }
    
    text {
      font-size: 28rpx;
      color: #999;
    }
  }
  
  .load-more {
    padding: px2rpx(30) 0;
    text-align: center;
    font-size: px2rpx(26);
    color: #999;
  }
}
</style>